<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use think\Request;
use think\Db;

/**
 * 游戏总分记录管理
 *
 * @icon fa fa-circle-o
 */
class Points extends Backend
{
    
    /**
     * Points模型对象
     * @var \app\admin\model\Points
     */
    protected $model = null;
    protected $searchFields = 'user.username,user.code';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Points;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $key => $row) {
                $row->visible(['id','total_score','createtime','user_id','updatetime','sort']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['username','code']);
                $wheres['total_score'] = ['>',$row['total_score']];
                $sort = Db::name('points')->where($wheres)->count();
                $list[$key]['sort'] = $sort + 1;
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }



    public function detail($userid){
        if(Request::instance()->get()){
            $result = Db::name('particular')->field("score,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as CreateDate")->where(['user_id'=>$userid])->order('createtime desc')->select();
            $arr = [];
            $arr['Image'] = $this->GetImage($userid);
            $arr['UserName'] = $this->GetUserName($userid);
            $arr['List'] = $result;
            //var_dump($arr);
            $this->assign('list',$arr);
        }
        return $this->view->fetch();
    }
    private function GetImage($userid){
        $image = Db::name('user')->field('image')->where(['id'=>$userid])->find();
        return $image['image'];
    }
    private function GetUserName($userid){
        $image = Db::name('user')->field('username')->where(['id'=>$userid])->find();
        return $image['username'];
    }


    /**
     * 导出获奖名单
     */
    public function export(){
        $objPHPExcel = new \PHPExcel;  //实例化PHPExcel类
        $objSheet = $objPHPExcel->getActiveSheet();
        $objSheet->getDefaultStyle()->getAlignment()
        ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)
        ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置默认字体及大小
        $objSheet->getDefaultStyle()->getFont()->setName('微软雅黑')->setSize('12');
        $objSheet->setTitle('免费门票');
        $data = Db::name('points')->field('user_id,total_score')->order('total_score desc')->limit(70)->select();
        $objSheet->setCellValue('A1','编号')
                 ->setCellValue('B1','用户名')
                 ->setCellValue('C1','最佳成绩')
                 ->setCellValue('D1','奖励');
        $j=2;
        //var_dump($data);
        foreach($data as $k => $v){
            $user = Db::name('user')->field('username,code')->where(['id'=>$v['user_id']])->find();
            $username = $this->filterEmoji($user['username']);
            $username = iconv('gb2312//ignore', 'utf-8', iconv('utf-8', 'gb2312//ignore', $username));
            $code = $user['code'];
            $score = $v['total_score'];
            $where['total_score'] = ['>',$v['total_score']];
            $sortcount = Db::name('points')->where($where)->count();
            $sort = $sortcount+1;
            if($sort <= 10){
                $win = '水公园日场入园一次';
            }else if($sort > 10 && $sort <= 30){
                $win = '水公园夜场入园一次';
            }else if($sort > 30 && $sort <= 70){
                $win = '精美礼品一份（园区自取）';
            }
            
            //var_dump($username);
            // if(strpos($username,'=') === 0){
            //     $username = "'".$username;
            // }
           
            $objSheet->setCellValue('A'.$j,$code)
                     ->setCellValue('B'.$j,$username)
                     ->setCellValue('C'.$j,$score)
                     ->setCellValue('D'.$j,$win);
            $j++;
        }
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
    $time = strtotime(date('Y-m-d H:i:s'));
    //$objWriter->save($time.'.xls');
    $this->Download('Excel5',$time.'.xls');
    $objWriter->save('php://output');
}



private function filterEmoji($emojiStr){
    $emojiStr = preg_replace_callback('/./u',function(array $match){
        return strlen($match[0]) >= 4 ? '' : $match[0];
    },$emojiStr);
    return $emojiStr;
}


private function Download($type,$filename){
    if($type == 'Excel5'){
        header('Content-Type: application/vnd.ms-excel');
    }else{
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    }
    header('Content-Disposition: attachment;filename="'.$filename.'"');
    header('Cache-Control: max-age=0');
}





}
